<?php

/*
	0 => width
	1 => height
	2 =& gt; 1 = GIF，2 = JPG，3 = PNG，4 = SWF，5 = PSD，6 = BMP，7 = TIFF(intel byte order)，8 = TIFF(motorola byte order)，9 = JPC，10 = JP2，11 = JPX，12 = JB2，13 = SWC，14 = IFF，15 = WBMP，16 = XBM
	3 => height="yyy" width="xxx"
 */

class Zend_Easthv_Image
{
	public static $type = array(
		"GIF" => 1,
		"JPG" => 2,
		"PNG" => 3,
		"SWF" => 4,
		"PSD" => 5,
		"BMP" => 6,
		"TIFF" => 7,
	);
	
	public static $info = array(
		"IMAGEWIDTH" => 0,
		"IMAGEHEIGHT" => 1,
		"IMAGETYPE" => 2,
	);
	
	public static function resizeByGd($src_file, $dest_file, $cut, $quantity="75",$method="gd2")
	{

		if(!function_exists('imagecreatefromjpeg')) {
			
			throw new Exception("PHP running on your server does not support the GD image library");
		
		}
	
		if ($method == "gd2" && !function_exists('imagecreatetruecolor')) {
			//change into GD1 automatic
			$method = 'gd';
			//throw new Exception("PHP running on your server does not support GD version 2.x, please change to GD version 1.x on your method");
		}

		//get infomation of iamge
		$imginfo = getimagesize($src_file);

		// GD can only handle JPG & PNG images
		if ($imginfo[self::$info['IMAGETYPE']] != self::$type['JPG'] && $imginfo[self::$info['IMAGETYPE']] != self::$type['PNG'] && ($method == 'gd1' || $method == 'gd2')){

			throw new Exception('File format not support');

		}

		if ($imginfo[self::$info['IMAGETYPE']] == self::$type['JPG']) {

			$src_img = imagecreatefromjpeg($src_file);

		} elseif($imginfo[self::$info['IMAGETYPE']] == self::$type['PNG']) {

			$src_img = imagecreatefrompng($src_file);

		} else {

			$src_img = imagecreatefromgif($src_file);

		}

		if (!$src_img){

			throw new Exception('Image reading failed');

		}

		try {

			switch ($method) {

			case "gd2" :

				$dst_img = imagecreatetruecolor($cut['dstW'], $cut['dstH']);

				imagecopyresampled($dst_img, $src_img, $cut['dstX'], $cut['dstY'], $cut['srcX'], $cut['srcY'], $cut['dstW'], $cut['dstH'], $cut['srcW'], $cut['srcH']);

				break;

			default :

				$dst_img = imagecreate($cut['dstW'], $cut['dstH']);

				imagecopyresized($dst_img, $src_img, $cut['dstX'], $cut['dstY'], $cut['srcX'], $cut['srcY'], $cut['dstW'], $cut['dstH'], $cut['srcW'], $cut['srcH']);

				break;

			}

			imagejpeg($dst_img, $dest_file, $quantity);

			imagedestroy($src_img);

			imagedestroy($dst_img);

			chmod($dest_file, 0777);

		}  catch (Exception $e) {

			throw $e;

		}

		try {

			//check generated image finally
			$imginfo = @getimagesize($dest_file);

			if ($imginfo == null){

				throw new Exception('Image writing failed');

			} 		

		}  catch (Exception $e) {

			@unlink($dest_file);
			throw $e;

		}

		return $imginfo;

	}
}
?>
